#include "mouse.h"



int mW_mouse_add_click(int x, int y, int buttons)
{
	
	mW_mouse_click * mouse_click;
	
	mouse_click = (mW_mouse_click *) malloc(sizeof(mW_mouse_click));
	
	mouse_click->x = x;
	mouse_click->y = y;
	mouse_click->buttons = buttons;
	
	mW_list_insert(mW_mouse_clicks, mouse_click);
	
	return 1;
	
}



int mW_mouse_delete_last_click()
{
	
	return mW_list_delete_last(mW_mouse_clicks);
	
}



int mW_mouse_delete_all_clicks ()
{
	
	return mW_list_delete_all(mW_mouse_clicks);
	
}



int mW_mouse_draw_pointer (BITMAP * surface)
{
	
	acquire_bitmap(surface);
	
	// blit mouse pointer
	masked_blit(mW_mouse_img_mouse_pointer,
	            surface,
	            0,
	            0,
	            mW_mouse_x,
	            mW_mouse_y,
	            mW_mouse_img_mouse_pointer->w,
	            mW_mouse_img_mouse_pointer->h);
	            
	release_bitmap(surface);

	return 1;
	
}



/*
 * returns null if there are no mouse_clicks
 */
mW_mouse_click * mW_mouse_get_last_click()
{
	
	return mW_list_get_last(mW_mouse_clicks);
	
}



mW_mouse_click * mW_mouse_get_next_click()
{
	
	return mW_list_iterate(mW_mouse_clicks, 1);
	
}



int mW_mouse_init()
{
	
	mW_mouse_buttons = 0;
	mW_mouse_x = 0;
	mW_mouse_y = 0;
	
	mW_mouse_clicks = mW_list_create();
	
	if (install_mouse() == -1)
		return 0;
	
	if (install_int_ex(mW_mouse_update, MSEC_TO_TIMER(33)) < 0)
		return 0;
	
	mW_mouse_img_mouse_pointer = load_bmp("data/interface_imgs/mouse_pointer.bmp", NULL);
	if (mW_mouse_img_mouse_pointer == NULL)
		return 0;
	
	return 1;
		
}



void mW_mouse_update ()
{
	
	volatile int mouse_position;
	volatile int mouse_buttons_tmp;
	
	poll_mouse();
	mouse_position = mouse_pos;
	mouse_buttons_tmp = mouse_b;
	mW_mouse_x = mouse_position >> 16;
	mW_mouse_y = mouse_position & 0x0000FFFF;
	
	// a button is pressed
	if ((mouse_buttons_tmp > 0) && (mouse_buttons_tmp != mW_mouse_buttons))
	{
		// add a new mouse click
		if (mW_mouse_add_click(mW_mouse_x, mW_mouse_y, mouse_buttons_tmp) == 0)
			printf("Error adding mouse click\n");
	}
	
	mW_mouse_buttons = mouse_buttons_tmp;

}



int mW_mouse_reset_iterator()
{
	
	return mW_list_reset_iterator(mW_mouse_clicks, 1);
	
}


